from django.shortcuts import render,redirect,reverse
from .models import News,NewsCategory,Comment,Banner
from django.conf import settings
from utils import restful
from .serializers import NewsSerializer,CommentSerializer
from django.http import JsonResponse, Http404
from .forms import PublicCommentForm
from apps.xfzauth.decorators import xfz_login_required
from apps.xfzauth.models import User
from django.db.models import Q


def index(request):
    news_count = settings.SINGLE_PAGE_NEWS_COUNT
    # all_news = News.objects.all()[:news_count] # 直接用这种形式，每个外键会多一次查询
    # 利用外键直接查询提高性能
    all_news = News.objects.select_related('category','author').all()[:news_count]
    categories = NewsCategory.objects.all()
    banners = Banner.objects.all()
    context = {
        'all_news':all_news,
        'categories':categories,
        'banners':banners
    }
    return render(request,'news/index.html',context=context)


def news_list(request):
    """
    通过p参数，来指定要获取第几页的数据
    """
    page = int(request.GET.get('p',1))
    category_id = int(request.GET.get('category_id',0))
    start = (page - 1) * settings.SINGLE_PAGE_NEWS_COUNT
    end = start + settings.SINGLE_PAGE_NEWS_COUNT

    if category_id == 0:
        news_per_page = News.objects.select_related('category','author').all()[start:end]
    else:
        news_per_page = News.objects.select_related('category','author').filter(category_id=category_id)[start:end]

    serializer = NewsSerializer(news_per_page,many=True)
    data = []
    for news in serializer.data:
        news.pop('content')
        data.append(news)
    return restful.result(data=data)


def news_detail(request, news_id):
    news = News.objects.select_related('category','author').filter(pk=news_id)
    comments = Comment.objects.select_related('author').filter(news_id=news_id)
    if news.exists():
        context = {
            'news':news[0],
            'comments':comments
        }
        return render(request,'news/news_detail.html',context=context)
    else:
        return Http404


def searched(request):
    keywords = request.GET.get('keywords')
    print(keywords)
    if keywords:
        result = (
            News.objects.select_related('category','author')
                .filter(Q(title__icontains=keywords)|Q(content__icontains=keywords))
        )
        context = {
            'result': result
        }
        return render(request,'news/searched.html',context=context)
    else:
        return render(request,'news/searched.html')


@xfz_login_required
def public_comment(request):
    form = PublicCommentForm(request.POST)
    if form.is_valid():
        news_id = form.cleaned_data.get('news_id')
        content = form.cleaned_data.get('content')
        news = News.objects.get(pk=news_id)
        comment = Comment.objects.create(content=content,news=news,author=request.user)
        serializer = CommentSerializer(comment)
        return restful.result(data=serializer.data)
    else:
        return restful.params_error(message='输入格式有误')






